package com.cxb.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.util.Log;
import android.widget.Toast;

import com.cxb.GuardActivity;
import com.cxb.utils.Debug;

public class PowerStateReceiver extends BroadcastReceiver {
	private static Context context = null;
	private static PowerToken powerToken = null;

	@Override
	public void onReceive(final Context mContext, Intent intent) {

		context = mContext;

		if (intent.getAction().equals(Intent.ACTION_BATTERY_CHANGED)) {

			int status = intent.getIntExtra("status",
					BatteryManager.BATTERY_STATUS_UNKNOWN);
			// Toast.makeText(mContext, "关机 status=" +
			// status, 1).show();
			Log.i("test", "power status=" + status);
			if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
				Log.i("test", "upload image usb 线拨出...");
				if (powerToken == null || powerToken.isPowerConnected()) {
					if (powerToken == null)
						powerToken = new PowerToken();
					powerToken.setPowerConnected(false);
					new Thread(new Runnable() {
						@Override
						public void run() {
							synchronized (powerToken) {
								try {
									powerToken.wait(3000);
								} catch (Exception e) {
									Debug.printf(e.toString(), null);
								}
							}
							// if (!powerToken.isPowerConnected()) {
							Log.i("test", "upload image powerToken wait 3000");

							Intent i = new Intent(context, GuardActivity.class/*
																			 * ShutdownActivity
																			 * .
																			 * class
																			 */);
							i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
									| Intent.FLAG_ACTIVITY_CLEAR_TOP);
							context.startActivity(i);
							// }
							// i = new Intent(context, MainActivity.class);
							//
							// i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
							// );
							// context.startActivity(i);

						}
					}).start();
				}

			} else {
				if (powerToken == null)
					powerToken = new PowerToken();
				powerToken.setPowerConnected(true);
				synchronized (powerToken) {
					powerToken.notifyAll();
				}
			}
			// else {
			// if (powerToken.isPowerConnected()) {
			// powerToken.setPowerConnected(false);
			//
			// }
			// }

		}
		// else if (intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
		// powerToken.setPowerConnected(true);
		// synchronized (powerToken) {
		// powerToken.notifyAll();
		// }
		// }
	}

	public static boolean IsPowerConnected() {

//		return false;
		if(Debug.DEBUG){
			return false;
		}
		if (powerToken == null)
			return true;
		return powerToken.isPowerConnected();
	}

	private class PowerToken {
		private boolean powerconnected = true;

		public void setPowerConnected(boolean connected) {
			this.powerconnected = connected;
		}

		public boolean isPowerConnected() {
			return (powerconnected == true);
		}
	}

}
